package com.bltec.emergency.common;

import com.bltec.emergency.model.Permission;
import com.bltec.emergency.service.mgrService.PermissionService;
import com.bltec.emergency.service.mgrService.RoleService;
import com.bltec.emergency.service.mgrService.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.List;

/**
 *  权限 拦截策略
 */
public class URLPathMatchingFilter extends PathMatchingFilter {
    @Autowired
    PermissionService permissionService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserService userService;

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        //防止LoginService注入失败
        /*if (loginService==null){
            loginService= SpringContextUtil.getContext().getBean(LoginService.class);
        }*/
        //请求的url
        String requestURL = getPathWithinApplication(request);
        System.out.println("请求的url :"+requestURL);
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            // 如果没有登录, 直接返回true 进入登录流程
            return  true;
        }
        String username = (String)SecurityUtils.getSubject().getSession().getAttribute("user");
        Long id = roleService.getRoleById(userService.getRoleIdByUserName(username)).getId();
        List<Permission> permissions = permissionService.getAllPermissionByRoleId(id);

        boolean hasPermission = false;
        for (Permission p : permissions) {

            if (p.getHref().equals(requestURL)){
                hasPermission = true;
                break;
            }
        }
        if (hasPermission){
            return true;
        }else {
            UnauthorizedException ex = new UnauthorizedException("当前用户没有访问路径" + requestURL + "的权限");
            subject.getSession().setAttribute("ex",ex);
            WebUtils.issueRedirect(request, response, "/unauthorized");
            return false;

        }

    }
}